package com.xxwy.dependency.injection.lazy;

import com.xxwy.dependency.User;
import com.xxwy.dependency.injection.qualifier.QualiferAnnotationDependenctInjectionDemo;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Set;

/**
 * 延迟注入
 * @author wy
 * @date 2020/4/27 15:47
 */
public class LazyAnnotationDependencyInjection {

  /**
   * 实时注入
   */
  @Autowired
  private User user;

  /**
   * 延迟注入，减少异常
   */
  @Autowired
  private ObjectProvider<User> objectProvider;

  /**
   * 延迟注入,objectFactory
   * @param args
   */
  @Autowired
  private ObjectFactory<Set<User>> userObjectFactory;

  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.register(LazyAnnotationDependencyInjection.class);
    XmlBeanDefinitionReader definitionReader = new XmlBeanDefinitionReader(context);
    int definitions = definitionReader.loadBeanDefinitions("classpath:/META-INF/dependency-lookup-context.xml");
    context.refresh();

    LazyAnnotationDependencyInjection bean = context.getBean(LazyAnnotationDependencyInjection.class);
    // 实时注入
    System.out.println("实时注入: " + bean.user);
    // 延迟注入单一
    System.out.println(bean.objectProvider.getIfAvailable());

    System.out.println("-----------------------------------------------");
    //延迟注入集合
    bean.objectProvider.forEach(System.out::println);

    System.out.println("-----------------------------------------------");

    // objectFactory
    System.out.println(bean.userObjectFactory.getObject());
  }
}
